// miniprogram/pages/courseInfo.js
// 后续会写一个下载的功能！！！
var app = getApp()
var transCommon = require('translation.js')
Page({

  data: {
    // 拖拽组件的参数
    ballTop: 0,
    ballLeft: 0,
    screenHeight: 0,
    screenWidth: 0,
    // 拖拽组件的参数
    currentIndex:-1,//当前点击翻译保存状态默认哪一个翻译按钮都不是
    totalTranslation : {},
    translationList:[],
    item: 0,
    tab: 0,
    playlist:[],//播放的录音列表
    state: 'paused',
    playIndex: 0,
    play: {
      currentTime: '00:00',
      duration: '00:00',
      percent: 0,
      title: '',
      singer: '',
      cover: ''
    },

    duration: 500,
    autoplay: false,

    imgList: [],//图片的集合
    queryIndex: -1,
    stv: {
      offsetX: 0,
      offsetY: 0,
      zoom: false, //是否缩放状态
      distance: 0, //两指距离
      scale: 1, //缩放倍数
    }
  },
  //从云开发数据库里列表
  getList() {
    //默认选择第一首
    
  },
  //从一大堆的翻译列表中获取单个单元的翻译
  getTrans:function(id){
    let iddd = id.toString();
    this.searchTrans(iddd);
  },
  searchTrans: function (id) {
    console.log("aaa");
    console.log() ;
    let tr = transCommon.searchTrans(id);
    this.setData({
      totalTranslation: tr
    })
    this.setData({
      translationList: tr["0"],
    })
  },
  //拖拽翻译
  handletouchmove: function (event) {
    console.log(event)
    let pageX = event.touches[0].pageX;
    let pageY = event.touches[0].pageY;
    //屏幕边界判断
    if (pageX < 120 || pageY < 120)
      return;
    if (pageX > this.data.screenWidth - 120)
      return;
    if (pageY > this.data.screenHeight - 120)
      return;
    this.setData({
      ballTop: event.touches[0].pageY - 120,
      ballLeft: event.touches[0].pageX - 120,
    });
  },
  //显示中文翻译
  showTranslation:function(e){
    // let index = e.currentTarget.dataset.index;
    let totalTranslation = this.data.totalTranslation;
    // console.log(translationList[index]);

    if (this.data.showfanyi) {//应该不展示翻译
        this.setData({
          // translationPart: translationList[index],
          translationList: [],
          showfanyi: false
        })
      }else{//展示翻译
        this.setData({
          translationList: totalTranslation,
          showfanyi: true //下一次就应该不展示翻译
       
        })

      }
   
    
  


  },

  audioCtx: null,
  onReady: function() {

    //创建InnerAudioComtext实例
    var audioCtx = wx.createInnerAudioContext()

    this.audioCtx = wx.createInnerAudioContext()

    var that = this

    //播放失败检测
    this.audioCtx.onError(function() {
      console.log('播放失败：' + that.audioCtx.src)
    })

    //播放完自动换下一曲
    this.audioCtx.onEnded(function() {
      // that.next()
    })

    //自动更新播放进度
    this.audioCtx.onPlay(function() {
      
    })
    this.audioCtx.onTimeUpdate(function() {
      that.setData({
        'play.duration': formatTime(that.audioCtx.duration),
        'play.currentTime': formatTime(that.audioCtx.currentTime),
        'play.percent': that.audioCtx.currentTime / that.audioCtx.duration * 100
      })
    })



    //格式化时间
    function formatTime(time) {
      var minute = Math.floor(time / 60) % 60;
      var second = Math.floor(time) % 60
      return (minute < 10 ? +minute : minute) + ':' + (second < 10 ? '0' + second : second)
    }
    this.setMusic(0);
  },

  // 播放与暂停
  play: function() {
    this.audioCtx.play()
    this.setData({
      state: 'running'
    })
  },

  pause: function() {
    this.audioCtx.pause()
    this.setData({
      state: 'paused'
    })
  },
  // 下一首
  next: function () {

    this.pause()

    var index = this.data.playIndex >= this.data.playlist.length - 1 ? 0 : this.data.playIndex + 1
    this.setMusic(index);
    this.play();
  },

  sliderChange: function (e) {
    var second = e.detail.value * this.audioCtx.duration / 100
    this.audioCtx.seek(second)
  },

  //换歌
  change: function (e) {
    this.setMusic(e.currentTarget.dataset.index)
    this.play()
  },
  setMusic: function (index) {
    var that = this
    var music = this.data.playlist[index]
    console.log('1', music);
    console.log(music)
    this.audioCtx.src = music;
    this.setData({
      playIndex: index,
      // 'play.currentTime': '00:00',
      // 'play.duration': '00:00',
      // 'play.percent': 0
    })
 
    
  },
  // 获取图片
  getImg: function(id) {
    var that = this;
    const db = wx.cloud.database();
    db.collection('tupianji').doc('5d1e07e5693b71d98e419260').get({
      success: function(res) {
        let arr = res.data
        let imgList = arr[id];
        // res.data 包含该记录的数据
        console.log(imgList)
        that.setData({
          imgList: imgList
        })
      }
    })

  },
  //获取录音
  getAudio: function (id) {
    var that = this;
    const db = wx.cloud.database();
    db.collection('luyinji').doc('5d25e291693b71d98e597a60').get({
      success: function (res) {
        let arr = res.data
        let playlist = arr[id];
        // res.data 包含该记录的数据
        console.log(playlist)
        that.setData({
          playlist: playlist
        })
      }
    })

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //获取屏幕宽高
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        _this.setData({
          screenHeight: res.windowHeight,
          screenWidth: res.windowWidth,
        });
      }
    });
   
    console.log(options);
    let id = options.id;
    // let id = 62;

    this.setData({
      id: options.id
    })
    this.getAudio(id);
    this.getImg(id);
    this.getTrans(id);





  },

  //事件处理函数
  touchstartCallback: function(e) {
    //触摸开始
    console.log('touchstartCallback');
    console.log(e);
    var index = e.currentTarget.dataset.index;
    console.log(typeof(index))

    this.setData({
      queryIndex: index
    })


    if (e.touches.length === 1) {
      let {
        clientX,
        clientY
      } = e.touches[0];
      this.startX = clientX;
      this.startY = clientY;
      this.touchStartEvent = e.touches;
    } else {
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);
      this.setData({
        'stv.distance': distance,
        'stv.zoom': true, //缩放状态
      })
    }

  },
  touchmoveCallback: function(e) {
    //触摸移动中
    //console.log('touchmoveCallback');
    //console.log(e);

    if (e.touches.length === 1) {
      //单指移动
      if (this.data.stv.zoom) {
        //缩放状态，不处理单指
        return;
      }
      let {
        clientX,
        clientY
      } = e.touches[0];
      let offsetX = clientX - this.startX;
      let offsetY = clientY - this.startY;
      this.startX = clientX;
      this.startY = clientY;
      let {
        stv
      } = this.data;
      stv.offsetX += offsetX;
      stv.offsetY += offsetY;
      stv.offsetLeftX = -stv.offsetX;
      stv.offsetLeftY = -stv.offsetLeftY;
      this.setData({
        stv: stv
      });

    } else {
      //双指缩放
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);

      let distanceDiff = distance - this.data.stv.distance;
      let newScale = this.data.stv.scale + 0.005 * distanceDiff;

      this.setData({
        'stv.distance': distance,
        'stv.scale': newScale,
      })
    }

  },
  touchendCallback: function(e) {
    //触摸结束
    console.log('touchendCallback');
    console.log(e);

    if (e.touches.length === 0) {
      this.setData({
        'stv.zoom': false, //重置缩放状态
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  

  /**
   * 生命周期函数--监听页面显示
   */
 
  onShow: function () {
    this.getList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  // 顶部的绿色的录音按钮点击之后调用playAudio函数去播放对应得录音
  playAudio: function(e){
    console.log(e);
    let index = e.currentTarget.dataset.index;
    console.log(index);
    this.setMusic(index);
    this.play();
  },
  fanye:function(e){
    let playList = this.data.playlist;
    console.log(e.detail)
    let detail = e.detail;
    if (detail.source =="touch"){
      let current = detail.current;
      console.log(current);
      this.setData({
        current: current, //当前swiper的页码
        translationList : this.data.totalTranslation[(current+1).toString()]
      })
      if(current>playList.length-1){
        current = playList.length-1
      }
      this.setData({
        luyinCurrent: current
      })

    }
  
    // e.detail = { current, source }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})